package emailserving.component;

import com.google.common.base.Preconditions;

import javax.mail.internet.MimeMessage;
import java.util.Map;


public class EmailTask extends Thread {
    private volatile boolean stopped = false;

    private Map<Long, MimeMessage> mimeMessageMap;
    private EmailSender sender;
    private EmailTaskCallback emailTaskCallback;


    public EmailTask(Map<Long, MimeMessage> mimeMessageMap, EmailSender sender) {
        Preconditions.checkNotNull(mimeMessageMap, "mimeMessageMap is null");
        Preconditions.checkNotNull(sender, "EmailSender is null");
        this.mimeMessageMap = mimeMessageMap;
        this.sender = sender;


    }

    @Override
    public void run() {
        for (Map.Entry<Long, MimeMessage> messageEntry : mimeMessageMap.entrySet()) {
            if (!stopped) {
                sender.send(messageEntry.getValue());
                emailTaskCallback.run(messageEntry.getKey());
            } else {
                break;
            }
        }
    }


    public EmailTask setCallback(EmailTaskCallback emailTaskCallback) {
        Preconditions.checkNotNull(emailTaskCallback);
        this.emailTaskCallback = emailTaskCallback;
        return this;
    }

    public boolean isStopped() {
        return stopped;
    }

    public void manualStop() {
        stopped = true;
    }
}
